const dayjs = require('dayjs')
const ms = require('ms')

module.exports = app => {
  const { Schema, model, getModelName } = app.jax.mongoose
  const modelName = getModelName(__filename)

  const requestLogSchema = new Schema({
    url: String,
    method: String,
    body: Schema.Types.Mixed,
    query: Schema.Types.Mixed,
    // session: Schema.Types.Mixed,
    headers: Schema.Types.Mixed,
    responseTime: Number, // 响应时间
    status: Number, // 响应状态

    apiCode: Number, // API响应状态
    response: String, // 响应数据
    stack: String, // 内容
    exception: String, // 异常
    ip: String, // IP
  })

  const Model = model(modelName, requestLogSchema)

  // 删除7天前数据
  setInterval(async () => {
    const before = dayjs().subtract(7, 'days').format('YYYY-MM-DD')
    const ret = await Model.deleteMany({
      createdAt: {
        $lte: before,
      },
    })
    console.log('[Model RequestLog] 自动删除过期数据', ret)
  }, ms('1h'))

  return Model
}
